package com.cqut.forum.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cqut.forum.entity.ArticleGroup;
import com.cqut.forum.entity.User;
import com.cqut.forum.service.ArticleGroupService;
import com.cqut.forum.service.ModuleService;

/**
 * 博客分组controller
 * @author yangxun
 */
@Controller
public class ArticleGroupAction {
	
	@Resource
	private ArticleGroupService articleGroupService;
	@Resource
	private ModuleService moduleService;
	
	@RequestMapping("/article/article_group")
	@ResponseBody
	public List<Map<String, Object>> articleGroups(HttpServletRequest request){
		User user = (User)request.getSession().getAttribute("user");
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		List<ArticleGroup> groups = articleGroupService.getByOwnerId(user.getUserId(), 0, 100);
		for(ArticleGroup ar:groups){
			Map<String, Object> m = new HashMap<String, Object>();
			m.put("groupId", ar.getArticleGroupId());
			m.put("groupName", ar.getArticleGroupName());
			result.add(m);
		}
		
		return result;
	}
	
	@RequestMapping("/article/create_group")
	@ResponseBody
	public String createGroup(HttpServletRequest request,String groupName){
		User user = (User)request.getSession().getAttribute("user");
		if(articleGroupService.getArticleGroup(groupName)!=null){
			return "已存在该组名";
		}
		ArticleGroup ag = new ArticleGroup();
		ag.setArticleGroupName(groupName);
		ag.setArticleGroupState(true);
		ag.setArticleNumber(0);
		ag.setOwnerId(user.getUserId());
		ag.setModuleId(moduleService.getModuleIndex("博客"));
		
		ag = articleGroupService.addArticleGroup(ag);
		if(ag==null)
			return "创建失败";
		else
			return "创建成功";
	}
	
	@RequestMapping("/garden/load_groups")
	@ResponseBody
	public List<Map<String, Object>> loadGardenGroup(){
		List<Map<String, Object>> groups = articleGroupService.loadGardenGroup();
		return groups;
	}
}
